<?php

/**
 * WeEngine System
 *
 * (c) We7Team 2021 <https://www.w7.cc>
 *
 * This is not a free software
 * Using it under the license terms
 * visited https://www.w7.cc for more details
 */

namespace app\controller;

use app\BaseController;
use app\model\News;

class NewsController extends BaseController
{
    public function list()
    {
        $list = (new News())->lists();
        return view('news/list', [
            'list' => $list,
        ]);
    }

    public function detail()
    {
        $data = ['id' => $this->request->get('id')];
        $this->validate($data, 'app\validate\News.detail');
        $newsInfo = News::find($data['id']);
        if (empty($newsInfo)) {
            throw new \RuntimeException('文章不存在！');
        }
        return view('news/detail', ['info' => $newsInfo]);
    }

    public function edit()
    {
        $data = ['id' => $this->request->get('id')];
        $this->validate($data, 'app\validate\News.edit');
        
        if (!empty($data['id'])) {
            $newsInfo = News::find($data['id']);
        } else {
            $newsInfo = [
                'title'       => '',
                'label'       => '',
                'description' => '',
                'content'     => '',
            ];
        }
        return view('news/edit', ['info' => $newsInfo]);
    }

    public function save()
    {
        $data = [
            'id'          => $this->request->post('id'),
            'title'       => $this->request->post('title'),
            'label'       => $this->request->post('label'),
            'description' => $this->request->post('description'),
            'content'     => $this->request->post('content'),
        ];
        $this->validate($data, 'app\validate\News.save');
        
        if ($data['id']) {
            $news = News::find($data['id']);
        } else {
            $news = new News();
        }
        $news->title       = $data['title'];
        $news->label       = $data['label'];
        $news->description = $data['description'];
        $news->content     = $data['content'];
        $news->createtime  = time();
        $news->save();
        return json(['code' => 0, 'message' => '保存成功!']);
    }

    public function delete()
    {
        $data = ['id' => $this->request->post('id')];
        $this->validate($data, 'app\validate\News.delete');
        News::destroy($data['id']);
        return json(['code' => 0, 'message' => '删除成功!']);
    }
}
